//
//  MenuSubViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/27.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "MenuHeaderView.h"
#import "MenuFooterView.h"

#import "MenuDetailListCell.h"

#import "MenuSubViewController.h"

@interface MenuSubViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) MenuHeaderView *headerView;

@property (nonatomic, strong) MenuFooterView *footerView;

@end

@implementation MenuSubViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (instancetype)initWithModel:(CommonMenuModel *)model {
    
    self = [super init];
    
    if (self) {
        self.model = model;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:@"BA_LoginSuccess" object:nil];
    [self prepareData1];
    //[self prepareData];
    [self initView];
}

- (void)loginSuccessAction {

    if (self.headerView && self.model) {
        [self.headerView fillCellWithModel:self.model];
    }
}
- (void)prepareData1 {
    NSString *jsonString = self.model.bhmMenuJson;
    if (jsonString.length == 0) {
        return;
    }
    NSDictionary *dic = [self handleStr:jsonString];
    NSArray *array = dic[@"array"];
    jsonString = dic[@"content"];
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if (json == nil && dic.allKeys.count == 2) {
        [self prepareData];
        return;
    }
    self.model.titleArray = [NSMutableArray array];
    NSArray *jsonArray = (NSArray *)json;
    for (NSInteger index = 0; index < jsonArray.count; index ++) {
        NSArray *itemArray = jsonArray[index];
        for (NSInteger flag = 0; flag < itemArray.count; flag ++) {
            [self.model.titleArray addObject:[NSString stringWithFormat:@"%@[%@]",itemArray[flag],array[index]]];
        }
    }
    
}
- (NSDictionary *)handleStr:(NSString *)jsonString
{
    /**
     {"冷菜":["金米山药炖活海参","年糕炒肉蟹"],"热菜":["至尊东坡肘子","唐府宫保大虾球","清蒸老虎斑","至尊海鲜汇"],"主食":["山盟海誓（虫草花菌菇佛跳墙）","丝瓜尖炒甜笋","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭","三文鱼炒饭"],"赠送":["步步登高（麻辣波士顿大龙虾）"]}
     */
    NSMutableArray<NSString *> *array = [[NSMutableArray alloc]init];
    for (NSInteger index = jsonString.length - 1; index >= 0 ; index --) {
        NSString *itemStr = [jsonString substringWithRange:NSMakeRange(index, 1)];
        if ([itemStr isEqualToString:@":"]) {
            NSDictionary *dic = [self handleSubStr:index withStr:jsonString];
            if (dic.allKeys.count == 3) {
                [array addObject:dic[@"content"]];
                NSNumber *leftNumber = dic[@"leftIndex"];
                NSNumber *lengthNumber = dic[@"length"];
                NSMutableString *tempStr = [NSMutableString string];
                [tempStr appendString:[jsonString substringToIndex:leftNumber.integerValue]];
                [tempStr appendString:[jsonString substringFromIndex:leftNumber.integerValue + lengthNumber.integerValue]];
                jsonString = tempStr;
            }
            
        }
    }
    NSMutableString *string = [NSMutableString string];
    [string appendString:@"["];
    [string appendString:[jsonString substringWithRange:NSMakeRange(1, jsonString.length - 2)]];
    [string appendString:@"]"];
    
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSInteger index = array.count - 1; index >= 0; index --) {
        NSString *title = array[index];
        title = [title substringWithRange:NSMakeRange(1, title.length - 3)];
        [mutableArray addObject:title];
    }
    array = mutableArray.copy;
    return @{@"array":array,@"content":string};
}
- (NSDictionary *)handleSubStr:(NSInteger)originIndex withStr:(NSString *)jsonString
{
    NSInteger again = 0;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSInteger index = originIndex; index >= 0 ; index --) {
        NSString *itemStr = [jsonString substringWithRange:NSMakeRange(index, 1)];
        if ([itemStr isEqualToString:@"\""]) {
            if (again == 1) {
                NSString *content = [jsonString substringWithRange:NSMakeRange(index, originIndex - index + 1)];
                [dic setValue:content forKey:@"content"];
                [dic setValue:[NSNumber numberWithInteger:index] forKey:@"leftIndex"];
                [dic setValue:[NSNumber numberWithInteger:originIndex - index + 1] forKey:@"length"];
                break;
            }
            again += 1;
        }
    }
    return dic;
}
- (void)prepareData {
    
    NSString *jsonString = self.model.bhmMenuJson;
    
    if (jsonString.length == 0) {
        return;
    }
    NSDictionary * jsonDic = @{}.mutableCopy;
    jsonDic = [Utilities convert2DictionaryWithJSONString:jsonString].mutableCopy;
    
    NSArray *sectionTitles = jsonDic.allKeys;
    self.model.titleArray = @[].mutableCopy;
    for (int i = 0; i < sectionTitles.count; i++) {
        
        NSString *sectionTitle = sectionTitles[i];
        NSArray *cellTitleArray = [jsonDic valueForKey:sectionTitle];   //一组cell的数据

        for (int j = 0; j < cellTitleArray.count; j++) {
            
            NSString *itemTitle = [NSString stringWithFormat:@"%@[%@]",cellTitleArray[j],sectionTitle];

            if (itemTitle.length > 0) {
                [self.model.titleArray addObject:itemTitle];
            }
        }
        
    }

}

- (void)initView {
    
    if([self.tableview respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }

    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];

    self.headerView =  [[NSBundle mainBundle] loadNibNamed:@"MenuHeaderView"owner:nil options:nil].firstObject;
    self.headerView.frame = CGRectMake(0, 0, TTScreenWidth, [MenuHeaderView calculateHeader]);

    self.tableview.tableHeaderView = self.headerView;
    self.headerView.autoresizingMask = UIViewAutoresizingNone;
    
    [self.headerView fillCellWithModel:self.model];
    
    self.footerView =  [[NSBundle mainBundle] loadNibNamed:@"MenuFooterView"owner:nil options:nil].firstObject;
    

    CGFloat labHeight = [Utilities getStringHeightWithText:self.model.bhmOrtherText font:[UIFont systemFontOfSize:14] viewWidth:(TTScreenWidth - 70)];
    CGFloat height = MAX(labHeight, 40) + 90;
    
    self.footerView.frame = CGRectMake(0, 0, TTScreenWidth, height);
    self.footerView.itemContentLab.text = self.model.bhmOrtherText;
    self.tableview.tableFooterView = self.footerView;
    self.footerView.autoresizingMask = UIViewAutoresizingNone;
    
    [self.tableview reloadData];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MenuDetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MenuDetailListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
//    [cell fillCellWithModel:self.dataArray[indexPath.section].goodsList[indexPath.row]];
    
    return cell;
}


- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        _tableview.backgroundColor =  UIColorHex(0xf7f7f7);
        _tableview.showsVerticalScrollIndicator = NO;
        
        [_tableview registerNib:[UINib nibWithNibName:@"MenuDetailListCell" bundle:nil] forCellReuseIdentifier:@"MenuDetailListCellID"];

        
    }
    return _tableview;
}

@end
